$(document).ready(function () {
    initDateTimeRangePick($('#TimeDay'));
    initSummaryTable();
    refreshTotalData();
    initTable();
    refreshHistogramData();
});

$.fn.serializeObject = function()
{
   var o = {};
   var a = this.serializeArray();
   $.each(a, function() {
       if (o[this.name]) {
           if (!o[this.name].push) {
               o[this.name] = [o[this.name]];
           }
           o[this.name].push(this.value || '');
       } else {
           o[this.name] = this.value || '';
       }
   });
   return o;
};

$('#theform_commit').click(function (){
      refreshTotalData();
      initTable();
      refreshHistogramData();
});

$("#histogramPrefix").change(function() {
      refreshHistogramData();
});



////////////////////////////*汇总方法开始*////////////////////////////////
var itemStyle = {
    normal: {
        opacity: 20,
        shadowBlur: 8,
        shadowOffsetX: 0,
        shadowOffsetY: 0,
        shadowColor: 'rgba(0, 0, 0, 0.5)'
    }
};

//设置直方图参数
function fillHistogramOptions(histogramData){
    option = {
        backgroundColor: '#404a59',
        color: ['#1db667'],
        tooltip : {
            trigger: 'axis',
            axisPointer : {            // 坐标轴指示器，坐标轴触发有效
                type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
            }
        },
        grid: {
            x: '90',
            x2: 200,
            y: '18%',
            y2: '10%'
        },
        xAxis :
            {
                name : histogramData.xAxisTitle,
                nameTextStyle: {
                    color: '#fff',
                    fontSize: 14
                },
                type : 'category',
                data : histogramData.titles,
                axisTick: {
                    alignWithLabel: true
                },
                axisLine: {
                    lineStyle: {
                        color: '#eee'
                    }
                }
            }
        ,
        yAxis :{
            name : histogramData.yAxisTitle,
            nameTextStyle: {
                color: '#fff',
                fontSize: 14
            },
            type : 'value',
            axisLine: {
                lineStyle: {
                    color: '#eee'
                }
            },
            splitLine:{
                show: false
            }
        },
        series : [
            {
                name:histogramData.yAxisTitle,
                type:'bar',
                barWidth: '60%',
                data:histogramData.histogramDatas
            }
        ]
    };
    // 基于准备好的dom，初始化echarts实例
    var histogramChart = echarts.init(document.getElementById('histogramChart'));

    //使用刚指定的配置项和数据显示图表。
     histogramChart.setOption(option);
}


//查询总数据（包括统计图）
function refreshTotalData(){
     var chartParams = $('#theform').serializeObject();
     var chartParamsString = JSON.stringify(chartParams);

     var scatterData = [];

     // 异步加载数据
     $.ajax({
        type: "post",
        async: true,            //异步请求（同步请求将会锁住浏览器，用户其他操作必须等待请求完成才可以执行）
        url: "/analytics/summaryTotalData.json",
        data: chartParamsString,
        contentType: 'application/json;charset=utf-8',
        dataType: "json",        //返回数据形式为json
        success: function (data) {

            if(data){
                var summaryData = data;
                refreshSummary(summaryData);
            }
         },
                error: function (errorMsg) {
                    //请求失败时执行该函数
                    alert("图表请求数据失败!");
                    myChart.hideLoading();
                }
            });
}

//刷新直方图
function refreshHistogramData(){
     var chartParams = $('#theform').serializeObject();
     var chartParamsString = JSON.stringify(chartParams);

     var scatterData = [];

     // 异步加载数据
    $.ajax({
        type: "post",
        async: true,            //异步请求（同步请求将会锁住浏览器，用户其他操作必须等待请求完成才可以执行）
        url: "/analytics/summaryHistogram.json",
        data: chartParamsString,
        contentType: 'application/json;charset=utf-8',
        dataType: "json",        //返回数据形式为json
        success: function (data) {
            if(data){
                fillHistogramOptions(data);
            }
        },
        error: function (errorMsg) {
            //请求失败时执行该函数
            alert("图表请求数据失败!");
        }
    });
}

//刷新汇总数据
function refreshSummary(summaryData){
    summaryrow = {
        requestCount: summaryData[0].value,
        esCount: summaryData[1].value,
        rdsCount: summaryData[2].value,
        jdbcExecuteCount: summaryData[3].value,
        concurrentMax: summaryData[4].value,
        esResTotal: summaryData[5].value,
        rdsResTotal: summaryData[6].value
    };
    $('#summarytable').bootstrapTable('updateRow', { index: 0, row:summaryrow });
}

//初始化汇总数据
function initSummaryTable(summaryData){
    $('#summarytable').bootstrapTable({
		data: [{}]
	});

}
////////////////////////////*汇总方法开始*////////////////////////////////

/////////////////////////////table 处理方法---开始//////////////////////////////////

//初始化表格
function initTable(){

    $('#thetable').bootstrapTable('destroy');
    $('#thetable').bootstrapTable({
      showExport: true,
      url: '/analytics/summary.json',
      method: 'post',
      queryParams: queryParams,
      responseHandler: responseHandler,
      idField: 'Time',
      classes: 'table table-hover table-condensed',
      striped: true,
      dataShowExport: true,
      sortStable: true,
      pagination: false,
      columns: [
        { field: 'Time',  title: '时间',        sortable: true },
        { field: 'requestCount', title:'请求数', formatter: numt },
        { field: 'concurrentMax', title:'最高并发', formatter: numt },
        { field: 'rdsCount', title:'REDIS执行', formatter: numt },
        { field: 'rdsCostTotal', title:'REDIS总耗时', formatter: numts },
        { field: 'rdsCostMax', title:'REDIS最大耗时', formatter: numts },
        { field: 'rdsResTotal', title:'REDIS总输出', formatter: nums },
        { field: 'esCount', title:'ES执行', formatter: numt },
        { field: 'esCostTotal', title:'ES总耗时', formatter: numts },
        { field: 'esCostMax', title:'ES最大耗时', formatter: numts },
        { field: 'esResTotal', title:'ES总输出', formatter: nums },
        { field: 'jdbcActivePeak', title:'JDBC高峰', formatter: numt },
        { field: 'jdbcPoolingPeak', title:'连接池高峰', formatter: numt },
        { field: 'jdbcExecuteCount', title:'JDBC执行数', formatter: numt },
        { field: 'jdbcErrorCount', title:'JDBC异常数', formatter: numt },
        { field: 'startTransactionCount', title:'开始事务', formatter: numt },
        { field: 'jdbcCommitCount', title:'提交事务', formatter: numt },
        { field: 'jdbcRollbackCount', title:'回滚次数', formatter: numt },
        { field: 'jdbcExecuteTimeMillis', title:'执行总耗时', formatter: numts },
        { field: 'jdbcFetchRowCount', title:'查询总行数', formatter: numt },
        { field: 'jdbcUpdateCount', title:'更新总行数', formatter: numt },
        { field: 'notEmptyWaitMillis', title:'非空等待总时长', formatter: numts },
        { field: 'botCount', title:'机器人访问次数', formatter: numt }
      ]
    });
}

//表格响应数据处理
function responseHandler(root) {
    $('#theader').html('表格 记录数:'+root.hits.total+', 搜索耗时:'+root.took+'ms, 分片:'+root._shards.successful +'/'+ root._shards.total);
    $('#desc').html(root.desc);

    var currentData = [];
    root.aggregations['group_by@@timestamp@@timestamp'].buckets.forEach(function (v) {
        currentData.push({
            Time: v['key_as_string'],
            requestCount:    v['sum@@timestamp@requestCount'].value,
            concurrentMax:    v['max@@timestamp@concurrentMax'].value,
            rdsCount:    v['sum@@timestamp@rdsCount'].value,
            rdsCostTotal:    v['sum@@timestamp@rdsCostTotal'].value,
            rdsCostMax:    v['max@@timestamp@rdsCostMax'].value,
            rdsResTotal:    v['sum@@timestamp@rdsResTotal'].value,
            esCount:    v['sum@@timestamp@esCount'].value,
            esCostTotal:    v['sum@@timestamp@esCostTotal'].value,
            esCostMax:    v['max@@timestamp@esCostMax'].value,
            esResTotal:    v['sum@@timestamp@esResTotal'].value,
            jdbcActivePeak:    v['max@@timestamp@jdbcActivePeak'].value,
            jdbcPoolingPeak:    v['max@@timestamp@jdbcPoolingPeak'].value,
            jdbcExecuteCount:    v['sum@@timestamp@jdbcExecuteCount'].value,
            jdbcErrorCount:    v['sum@@timestamp@jdbcErrorCount'].value,
            startTransactionCount:    v['sum@@timestamp@startTransactionCount'].value,
            jdbcCommitCount:    v['sum@@timestamp@jdbcCommitCount'].value,
            jdbcRollbackCount:    v['sum@@timestamp@jdbcRollbackCount'].value,
            jdbcExecuteTimeMillis:    v['sum@@timestamp@jdbcExecuteTimeMillis'].value,
            jdbcFetchRowCount:    v['sum@@timestamp@jdbcFetchRowCount'].value,
            jdbcUpdateCount:    v['sum@@timestamp@jdbcUpdateCount'].value,
            notEmptyWaitMillis:    v['sum@@timestamp@notEmptyWaitMillis'].value,
            botCount:    v['sum@@timestamp@botCount'].value

        });
    });
    return currentData;
  }

//表格请求参数处理
function queryParams(params) {
   $('#theform').serializeArray().forEach(function fn(v){
     params[v.name] = v.value;
   });
   return params;
}

/////////////////////////////table 处理方法---结束//////////////////////////////////




